#version 300 es
precision mediump float;
in vec2 votextture;
uniform vec2 texSize;
uniform lowp sampler2D s_textureY;
uniform lowp sampler2D s_textureU;
uniform lowp sampler2D s_textureV;
out vec4 outColor;
vec4 YuvToRgb(vec2 uv) {
    float y, u, v, r, g, b;
    y = texture(s_textureY, uv).r;
    u = texture(s_textureU, uv).r;
    v = texture(s_textureV, uv).r;
    u = u - 0.5;
    v = v - 0.5;
    r = y + 1.403 * v;
    g = y - 0.344 * u - 0.714 * v;
    b = y + 1.770 * u;
    return vec4(r, g, b, 1.0);
}

float k1 = -0.454201041;
float k2 = 0.266614672;
float k3 = -0.0967655739;
float p1 = 0.000374852494;
float p2 = 0.000804914931;
float fx = 909.4744067;
float fy = 904.47449409;
float cx = 629.98081148;
float cy = 383.88105564;
float bilinear(float in00, float in01, float in10, float in11, float x, float y)
{   float tem= in00 + (in01 - in00) * x + (in10 - in00) * y
    + (in11 - in01 - in10 + in00) * x * y;
    return tem;
}
void main() {
        vec2 pos = votextture.xy;
       vec2 onePixel = vec2(1, 1) / texSize;
         //图片的坐标位置
        vec2 relpos=votextture.xy*texSize;

        float y=(relpos.y-cy)/fy;
        float x = (relpos.x - cx) / fx;
        float r2 =pow( relpos.x,2.0)  +pow( relpos.y,2.0) ;
        float scale = 1.0f + k1 * r2 + k2*pow(r2,2.0) + k3 *pow(r2,3.0);
        float xx = x * scale + 2.0f * p1 * x * y + p2 * (r2 + 2.0f * x * x);
        float yy = y * scale + p1 * (r2 + 2.0f *pow(y,2.0)) + 2.0f * p2 * x * y;
        float uu = (xx * fx + cx);
        float vv = (yy * fy + cy);
        //归一化位置 用来采样器采样
        float nouu=uu;
        float novv=vv;
        vec2 samplePos=(vec2(nouu,novv)+vec2(0,0))*onePixel;
        vec2 samplePos1=(vec2(nouu,novv)+vec2(1,0))*onePixel;
        vec2 samplePos2=(vec2(nouu,novv)+vec2(0,1))*onePixel;
        vec2 samplePos3=(vec2(nouu,novv)+vec2(1,1))*onePixel;
         //还原到正常的颜色  用来线性插值
        vec4 sampleColor=YuvToRgb(samplePos)*255.0;
       vec4 sampleColor1=YuvToRgb(samplePos1)*255.0;
       vec4 sampleColor2=YuvToRgb(samplePos2)*255.0;
       vec4 sampleColor3=YuvToRgb(samplePos3)*255.0;

        float a=bilinear(sampleColor.r,
        sampleColor1.r,sampleColor2.r
        ,sampleColor3.r,fract(nouu),fract(novv));
////
        float r=bilinear(sampleColor.g,
        sampleColor1.g,sampleColor2.g
       ,sampleColor3.g,fract(nouu),fract(novv));
////
        float g=bilinear(sampleColor.b,
        sampleColor1.b,sampleColor2.b
       ,sampleColor3.b,fract(nouu),fract(novv));
        //归一化采样 输出
        outColor=vec4(a/255.0,r/255.0,g/255.0,1.0f);
}


